package com.milhouz.findmydroid.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

public class AppProvider extends ContentProvider {

	private AppOpenHelper mOpenHelper;

	private SQLiteDatabase mDB;

	public static final String PROVIDER_NAME = "com.milhouz.findmydroid.db.AppProvider";
	public static final Uri CHARACTERS_URI = Uri.parse("content://" + PROVIDER_NAME + "/characters");
	public static final Uri CATEGORIES_URI = Uri.parse("content://" + PROVIDER_NAME + "/categories");
	public static final Uri CATEGORY_NAME_URI = Uri.parse("content://" + PROVIDER_NAME + "/categoryname");

	private static final int CHARACTERS = 1;
	private static final int CHARACTER_ID = 2;
	private static final int CATEGORIES = 3;
	private static final int CATEGORY_ID = 4;
	private static final int CHARACTERS_BY_CATEGORY_ID = 5;
	private static final int CATEGORY_NAME = 6;

	private static final UriMatcher URI_MATCHER;
	static {
		URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		URI_MATCHER.addURI(PROVIDER_NAME, "characters", CHARACTERS);
		URI_MATCHER.addURI(PROVIDER_NAME, "characters/#", CHARACTER_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "categories", CATEGORIES);
		URI_MATCHER.addURI(PROVIDER_NAME, "categories/#", CATEGORY_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "characters/category/#", CHARACTERS_BY_CATEGORY_ID);
		URI_MATCHER.addURI(PROVIDER_NAME, "categoryname/#", CATEGORY_NAME);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new AppOpenHelper(getContext());
		mDB = mOpenHelper.getWritableDatabase();
		return (mDB == null) ? false : true;
	}

	@Override
	public String getType(Uri uri) {
		switch (URI_MATCHER.match(uri)) {
		case CHARACTERS:
			return "vnd.android.cursor.dir/vnd.findmydroid.questions";
		case CHARACTER_ID:
			return "vnd.android.cursor.item/vnd.findmydroid.question";
		case CATEGORIES:
			return "vnd.android.cursor.dir/vnd.findmydroid.categories";
		case CATEGORY_ID:
			return "vnd.android.cursor.item/vnd.findmydroid.category";
		case CHARACTERS_BY_CATEGORY_ID:
			return "vnd.android.cursor.dir/vnd.findmydroid.questionscat";
		case CATEGORY_NAME:
			return "vnd.android.cursor.item/vnd.findmydroid.categoryname";
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		// Choose the table to request following the URI
		if (URI_MATCHER.match(uri) == CATEGORY_ID || URI_MATCHER.match(uri) == CATEGORIES) {
			sqlBuilder.setTables(AppConstants.TABLE_NAME_CATEGORIES);
		} else if (URI_MATCHER.match(uri) == -1) { // XXX BUG DU CATEGORY_NAME_URI
			sqlBuilder.setTables(AppConstants.TABLE_NAME_CATEGORIES);
		} else {
			sqlBuilder.setTables(AppConstants.TABLE_NAME_CHARACTERS);
		}
		// Choose the conditions request following the URI
		if (URI_MATCHER.match(uri) == CHARACTER_ID) {
			// Querying a particular question
			sqlBuilder.appendWhere(AppConstants.COLUMN_ID + " = " + uri.getPathSegments().get(1));
		} else if (URI_MATCHER.match(uri) == CATEGORY_ID) {
			// Querying a particular category by id
			sqlBuilder.appendWhere(AppConstants.COLUMN_ID + " = " + uri.getPathSegments().get(1));
		} else if (URI_MATCHER.match(uri) == CHARACTERS_BY_CATEGORY_ID) {
			// Querying all questions of a category
			sqlBuilder.appendWhere(AppConstants.COLUMN_CATEGORY_ID + " = " + uri.getPathSegments().get(2));
		} else if (URI_MATCHER.match(uri) == -1 && uri.getPathSegments().size() > 1) { // XXX BUG DU CATEGORY_NAME_URI
			sqlBuilder.appendWhere(AppConstants.COLUMN_NAME + " = \"" + uri.getPathSegments().get(1) + "\"");
		}
		Cursor c = sqlBuilder.query(mDB //
				, projection //
				, selection //
				, selectionArgs //
				, null //
				, null //
				, sortOrder);

		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long rowID = 0;
		Uri uriWithId = null;
		switch (URI_MATCHER.match(uri)) {
		case CHARACTERS:
			rowID = mDB.insert(AppConstants.TABLE_NAME_CHARACTERS, "", values);
			if (rowID > 0) { // if added successfully
				uriWithId = ContentUris.withAppendedId(CHARACTERS_URI, rowID);
			}
			break;
		case CATEGORIES:
			rowID = mDB.insert(AppConstants.TABLE_NAME_CATEGORIES, "", values);
			if (rowID > 0) { // if added successfully
				uriWithId = ContentUris.withAppendedId(CATEGORIES_URI, rowID);
			}
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		if (uriWithId != null) {
			getContext().getContentResolver().notifyChange(uriWithId, null);
			return uriWithId;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
		throw new SQLException("Update not allowed with the AppProvider : " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int count = 0;
		switch (URI_MATCHER.match(uri)) {
		case CHARACTERS:
			Log.i(AppConstants.TAG, "Delete characters");
			count = mDB.delete(AppConstants.TABLE_NAME_CHARACTERS, selection, selectionArgs);
			break;
		case CATEGORIES:
			Log.i(AppConstants.TAG, "Delete categories");
			count = mDB.delete(AppConstants.TABLE_NAME_CATEGORIES, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	public int getCategoryMaxId() {
		String query = "SELECT MAX(" + AppConstants.COLUMN_ID + ") FROM " + AppConstants.TABLE_NAME_CATEGORIES;
		Cursor cursor = mDB.rawQuery(query, null);
		int id = 0;
		if (cursor.moveToFirst()) {
			do {
				id = cursor.getInt(0);
			} while (cursor.moveToNext());
		}
		return id;
	}

}
